<?php

declare(strict_types=1);

namespace sheep\channel;

use think\Model;
use think\facade\Log;
use think\facade\Validate;
use yunwuxin\Notification;
use yunwuxin\notification\Channel;
use yunwuxin\notification\Notifiable;
use sheep\library\sms\message\NoticeMessage;
use sheep\facade\Sms as SmsFacade;

class Sms extends Channel
{

    public function __construct()
    {
    }


    /**
     * 发送短信通知
     * 
     * @param Notifiable   $notifiable
     * @param Notification $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        $params = $this->getMessage($notifiable, $notification);

        if ($params && $params['mobile'] && isset($params['template_id'])) {
            $mobile = $params['mobile'];
            $sendData = $params['data'] ?? [];
            ksort($sendData);   // 腾讯云短信，需要升序排列

            $params = [
                'data'      => $sendData,
                'template' => $params['template_id'],
                'default_content' => $notification->template['MessageDefaultContent'] ?? null
            ];

            try {
                // 设置消息
                $message = (new NoticeMessage)->init($mobile, $notification->event)->setParams($params);
                // 发送通知消息
                $result = SmsFacade::sendNotice($mobile, $message);

                // 发送成功
                $notification->sendOk('Sms');
            } catch (\Exception $e) {
                // 因为配置较麻烦，这里捕获异常防止因为缺少字段，导致队列一直执行不成功
                Log::error('短信发送失败，捕获异常：用户：' . $notifiable['id'] . '；类型：' . get_class($notification) . "；发送类型：" . $notification->event . "；错误信息：" . $e->getMessage());
            }

            return true;
        }
        // 没有手机号
        Log::error('短信发送失败，没有手机号：用户：' . $notifiable['id'] . '；类型：' . get_class($notification) . "；发送类型：" . $notification->event);

        return false;
    }
}
